class EntryController < ApplicationController
  
  require "net/pop"
  require "tmail"
  require "ruby-exif"
  require "base64"
  require "open-uri"
  require "rexml/document"

  in_place_edit_for :entry, :subject
  in_place_edit_for :entry, :body

  def initialize()
    @pop_server = 'localhost'
    @pop_port = 110
    @pop_user = 'entry'
    @pop_passwd = 'pass'
  end

  def index
    @entry_pages, @entries = paginate :entries, :per_page => 10, :order => 'entry_at DESC'
  end
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
      redirect_to :action => 'myalbum'
  end

  def myalbum
    if logged_in?
      @entry_pages, @entries = paginate :entries, :per_page => 3, :order => 'entry_at DESC', :conditions => "user_id = #{current_user.id}"
    else
      redirect_to :controller => 'account', :action => 'login'
    end
  end

  def show
    @entry = Entry.find(params[:id])
    @entry.counter = @entry.counter.to_i + 1
    @entry.update
  end

  def new
    @entry = Entry.new
  end

  def upload
    @entry = Entry.new
  end

  def create
    @entry = Entry.new(params[:entry])
    #if @entry.save
      #flash[:notice] = ''
          lat = params[:spot][:lat]
          lng = params[:spot][:long]
          Entry.post_entry({
            :spot_name => get_address(lat,lng).toutf8,
            :lat => lat,
            :long => lng,
            :user_id => @entry.user_id,
            :subject => @entry.subject,
            :body => @entry.body,
            :visible => @entry.visible,
            :picture_url => @entry.picture_url,
            :entry_at => @entry.created_at,
            :weather => get_weather(lat,lng).toutf8,
            :feeling => @entry.feeling
          })
      redirect_to :action => 'list'
    #else
      #render :action => 'new'
    #end
  end

  def edit
    @entry = Entry.find(params[:id])
    if logged_in? && (current_user.id == @entry.user_id)
      @entry
    else
      redirect_to :action => 'login'
    end
  end

  def update
    @entry = Entry.find(params[:id])
    if @entry.update_attributes(params[:entry])
      flash[:notice] = 'たびがきざまれました'
      redirect_to :action => 'show', :id => @entry
    else
      render :action => 'edit'
    end
  end

  def destroy
    Entry.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
  
  def get_entry_from_mail
    
    pop = Net::POP3.new(@pop_server, @pop_port)
    pop.start(@pop_user, @pop_passwd)
    
    #メールボックスが空
    if pop.mails.empty? then
      # 'no mail.'
      
    else
      i = 0
      pop.each_mail do |m|
        mail = TMail::Mail.parse(m.pop)
        
        #multipartじゃないのははじく
        if mail.multipart?
          
          subject = encode_field(mail.subject)
          from = TMail::Address.parse(mail.from[0]).spec
          user_id = User.find(:first, :conditions => "email = '#{from}'")["id"].to_i
          if user_id.nil?
            #登録されていないメールアドレスから届いた場合，
            #ゲストとして登録
            user_id = 0
          end
          picture = Time.now.to_f.to_s + '.jpg'
          picture_path = PICTURES_ROOT + picture
          
          
          mail.parts.each do |part|
            ct = part['Content-Type'].to_s
            if (ct =~ /^text\/plain\;.*?/)
              @body = part.body.toutf8
            elsif(ct =~ /^image\/jpeg\;.*?/)
              #ファイル書き込み
              File.open(picture_path, "wb") do |f|
                f.write part.body
              end
            end
          end

          # Jpegがなかった
          unless FileTest.exist?(picture_path)
            next
          end
          
          if (mail.from[0] =~ /.*@docomo.ne.jp$/)
            lat, lng, date = get_info_from_body(@body)
            if (lat == "")
              lat, lng, date = get_info_from_exif(picture_path)
            end
          else
            lat, lng, date = get_info_from_exif(picture_path)
          end
          
          feel = "Good!" #要修正
          
          #...
          entry = Entry.post_entry({
            :spot_name => get_address(lat ,lng).toutf8,
            :lat => lat,
            :long => lng,
            :user_id => user_id,
            :subject => subject,
            :body => @body,
            :visible => true,
            :picture_url => picture,
            :entry_at => date,
            :weather => get_weather(lat,lng).toutf8,
            :feeling => feel
          })
        end
        
        m.delete
        i += 1
      end
      # "mails popped."
    end
    
    pop.finish
    #redirect_to :action => 'list'
  end
  
  def get_info_from_body(body)
    @lat = ""
    @lon = ""
    unless body.nil?
      body.each_line do |x|
        if (x =~ /^.*http\:\/\/docomo\.ne\.jp\/cp\/map\.cgi\?lat\=\%2B(.*?)\&lon\=\%2B(.*?)\&.*/)
          @lat = dms2ddd($1)
          @lon = dms2ddd($2)
          break
        end
      end
    end
    [@lat, @lon, Time.now]
  end
  
  def get_info_from_exif(picture)
    if (FileTest.file?(picture))
      e = Exif.new(picture)
      unless e.info["GPSLatitude"].nil? || e.info["GPSLongitude"].nil?
        # *.*.*.*形式をfloatに変換して返す
        return [dms2ddd(e.info["GPSLatitude"]), dms2ddd(e.info["GPSLongitude"]), Time.now]
      end
    end
    # GPS情報がないときはランダムにｗ
    return [33.0 + rand(0), 130.0 + rand(0), Time.now]
  end
  
  
  
  def get_weather(lat, lon)
    
      #### get the weather link for the point of an input.
      xml_getlinkuri = URI.parse("http://ongmap.com/api?v=1.0&data=weather&lat=#{lat}&lng=#{lon}")
      getlinkxml = xml_getlinkuri.read
      getlinkdoc = REXML::Document.new getlinkxml
      # puts getlinkdoc
      link = getlinkdoc.elements["//ONGMAP/Result/Item/Link"]
      
      #### get the weather information using the acuired link.
      xml_wturi = URI.parse(link.text + "&day=today")
      wtxml = xml_wturi.read
      wtdoc = REXML::Document.new wtxml
      # puts wtdoc
      telop = wtdoc.elements["//telop"]
      if telop.nil?
        return wtdoc.elements["//yweather:condition"].attributes["text"]
      else
        return telop.text
      end
    end
    
    def encode_field (field)
      field.toeuc.gsub(/[　-瑤]\S*\s*/) {|x|
        x.scan(/.{1,10}/).map {|y|
        "=?iso-2022-jp?B?" + y.tojis.to_a.pack('m').chomp + "?="
      }.join("\n ")
    }.toutf8
  end

  def get_address(lat,lon)
    #### get the weather link for the point of an input.
    xml_getlinkuri = URI.parse("http://api.alpslab.jp/v1/level?appid=guest&p=#{ddd2sldms(lat,true)},#{ddd2sldms(lon,false)}")
    getlinkxml = xml_getlinkuri.read
    getlinkdoc = REXML::Document.new getlinkxml
    # puts getlinkdoc
    link = getlinkdoc.elements["//result/address"]
    return link.text
  end
  
  def dms2ddd(dms)
  # *.*.*.*形式を*.****形式に直す．
    dms =~ /(\d*?)\.(\d*?)\.(\d*?\.\d*?)/
    return ($1.to_f + ($2.to_f / 60) + ($3.to_f / 3600))
  end
  def ddd2sldms(ddd,lat)
  # *.****形式を*.*.*.*形式に直す．
    if lat
      ddd = ddd.to_f - (0.01 / 3)
    else
      ddd = ddd.to_f + (0.01 / 3)
    end
    d = ddd.to_i
    m = ((ddd - ddd.to_i) * 60).to_i
    s = ((ddd - ddd.to_i) * 60 % 1 * 60)
    return "#{d}/#{m}/#{s}"
  end

  def add_entry_from_file
    uploaded = params[:upload]["file"]
    picture = Time.now.to_f.to_s + '.jpg'
    picture_path = PICTURES_ROOT + picture
    if uploaded.class == Tempfile
      if jpeg?(uploaded.path)
        FileUtils.cp(uploaded.path, picture_path)
        
        lat, lng, date = get_info_from_exif(picture_path)
        
        entry = Entry.post_entry({
          :spot_name => get_address(lat ,lng),
          :lat => lat,
          :long => lng,
          :user_id => current_user.id,
          :subject => "",
          :body => "",
          :visible => true,
          :picture_url => picture,
          :entry_at => date,
          :weather => get_weather(lat,lng).toutf8,
          :feeling => "Good!"
        })
        
        flash[:notice] = "アップロードに成功しました"
      else
        flash[:notice] = "Jpegファイルではありません"
      end
    else
      flash[:notice] = "アップロードに失敗しました"
    end
    redirect_to :action => "upload"
  end

  def jpeg?(filename)
    if FileTest.file?(filename)
      f = File.open(filename, "rb")
      tmp = f.read(2)
      f.close
      tmp == "\377\330"
    else
      false
    end
  end

  def search
    #render :action => 'under_construction'
  end
  
  def search_result
    @words = params[:words].split.uniq.collect{|e| "%#{e}%"}
    
    if @words.empty?
      flash[:notice] = '検索語を入力してください'
      redirect_to :action => 'search'
      return
    end
    
    sql = "body like ?"
    (@words.size - 1).times do
      sql += " and body like ?"
    end
    @entries = Entry.find(:all, :conditions => [sql, *@words], :order => "entry_at DESC")
  end

  def under_construction
  end
  
  def help
  end

  def concept
  end

  def json_timeline
    entry = Entry.find(:all)
    result = entry.collect do |entry|
      {
        'start' => entry.created_at.strftime("%b %d %Y %H:%M:%S"),
        'title' => entry.subject,
        'description' => entry.body
      }
    end
    result = {'events' => result}
    logger.debug("result.to_json => #{result.to_json}")
    render :text => result.to_json
  end
  
  def ranking
    @ranking_data = Entry.find(:all, :order => 'counter DESC', :limit => 10)
    render(:layout => false)
  end

end
